﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using SmsVotes.DataAccess;
using System.Web.UI.DataVisualization.Charting;
using System.Drawing;
using System.Web.UI.HtmlControls;

namespace SmsVotes.SmsVoting
{
    public partial class CurrentQuestion : System.Web.UI.UserControl
    {
        public int? StateID
        {
            get { return ViewState["StateID"] as int?; }
            set { ViewState["StateID"] = value; }
        }



        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
                if (StateID == null)
                    StateID = int.Parse(Request.QueryString["sid"]);
            // Загружаем данные
            BindResults();

        }

        private void BindResults()
        {
            // Достаём состояние
            var currentState = StateManager.GetVoteStateByID((int)StateID);
            var currentQuestion = currentState.CurrentQuestion;
            if (currentState.Ended && !String.IsNullOrEmpty(Request.QueryString["qid"]))
            {
                var questionID = Convert.ToInt32(Request.QueryString["qid"]);
                currentQuestion = QuestionManager.GetByID(questionID);
            }
            // Заполняем титул графика
            FillTitle(currentQuestion);

            int totalVotes = StateManager.TotalVotes(currentState);

            // Заполняем массив точек
            FillSeries(currentQuestion, totalVotes);

            // Инициализируем оси
            cResults.ChartAreas["caResults"].AxisY.Maximum = 100;


            FillLabels(currentState, totalVotes);

        }

        /// <summary>
        /// Заполняем лейблы
        /// </summary>
        /// <param name="currentState"></param>
        /// <param name="totalVotes"></param>
        private void FillLabels(VoteState currentState, int totalVotes)
        {
            // Заполняем остальные данные
            lblTitle.Text = currentState.Vote.Name;
            lblSMSNumber.Text = currentState.Vote.Phone;
            lblTotalVotes.Text = totalVotes.ToString();
        }

        /// <summary>
        /// Заполняем массив точек
        /// </summary>
        /// <param name="currentQuestion"></param>
        /// <param name="totalVotes"></param>
        private void FillSeries(SmsVotes.DataAccess.Question currentQuestion, int totalVotes)
        {
            var series = new Series();
            // Определяем тип графика и создаём легенду для кругового графика
            if (currentQuestion.Chart.ID == 1)
                series.ChartType = SeriesChartType.Column;
            if (currentQuestion.Chart.ID == 2)
            {
                series.ChartType = SeriesChartType.Pie;
                var legend = new Legend();
                series.Legend = legend.Name;
                cResults.Legends.Add(legend);
            }
            FillSeriesPoints(currentQuestion, totalVotes, series);
            cResults.Series.Add(series);
        }

        private void FillSeriesPoints(SmsVotes.DataAccess.Question currentQuestion, int totalVotes, Series series)
        {
            currentQuestion.Answers.SmartLoad(currentQuestion);
            if (totalVotes > 0)
                foreach (var answer in currentQuestion.Answers)
                {
                    var nVotes = StateManager.AnswerVotes(answer, StateID.Value);

                    // Заполняем данные на графике
                    var point = new DataPoint();
                    point.LegendText = answer.Name;
                    point.SetValueY(100 * nVotes / totalVotes);
                    if (currentQuestion.Chart.ID == 1)
                        point.Label = answer.Name;
                    if (currentQuestion.Chart.ID == 2)
                    {
                        point.Label = nVotes.ToString();
                    }
                    series.Points.Add(point);

                    // Заполняем данные в таблице
                    var row = new HtmlTableRow();
                    row.Cells.Add(new HtmlTableCell() { InnerText = answer.Name });
                    row.Cells.Add(new HtmlTableCell() { InnerText = nVotes.ToString() });
                    tableResults.Rows.Add(row);

                }
        }

        /// <summary>
        /// Заполняем заголовок графика
        /// </summary>
        /// <param name="currentQuestion"></param>
        private void FillTitle(SmsVotes.DataAccess.Question currentQuestion)
        {
            var title = new Title(currentQuestion.Name, Docking.Top, new Font(FontFamily.GenericSerif, 14), Color.Black);
            cResults.Titles.Add(title);
        }
    }
}